// 敌人类
class Enemy {
    constructor(type, floor, isElite = false, isBoss = false, difficultyTier = 1) {
        this.type = type;
        this.floor = floor;
        this.isElite = isElite;
        this.isBoss = isBoss;
        this.difficultyTier = difficultyTier || 1;
        this.initializeStats();
        this.applyDifficultyScaling();
        this.initializePattern();
    }

    // 初始化属性
    initializeStats() {
        const baseHealth = this.getBaseHealth();
        const baseDamage = this.getBaseDamage();
        // 优化层数成长：改为每层+8%，让成长更平缓
        const floorMultiplier = 1 + (this.floor - 1) * 0.08;
        
        this.maxHealth = Math.floor(baseHealth * floorMultiplier);
        this.health = this.maxHealth;
        this.baseDamage = Math.floor(baseDamage * floorMultiplier);
        this.goldReward = this.getGoldReward();
        this.name = this.getName();
        this.description = this.getDescription();
        
        this.pattern = [];
        this.patternIndex = 0;
        this.intent = '';
        this.statuses = []; // 敌人状态列表
        this.statusManager = new StatusManager(); // 敌人状态管理器
    }

    applyDifficultyScaling() {
        if (this.difficultyTier <= 1) return;
        const tier = this.difficultyTier - 1;
        const healthMultiplier = 1 + tier * 0.12;
        const damageMultiplier = 1 + tier * 0.1;
        this.maxHealth = Math.floor(this.maxHealth * healthMultiplier);
        this.health = this.maxHealth;
        this.baseDamage = Math.floor(this.baseDamage * damageMultiplier);
        this.goldReward += tier * (this.isBoss ? 40 : this.isElite ? 25 : 15);
    }

    // 获取基础生命值（优化后：降低基础血量，让战斗更快节奏）
    getBaseHealth() {
        if (this.isBoss) return 120;  // 从200降到120
        if (this.isElite) return 60;   // 再降一档，缓解前期精英压力
        return 35;                     // 从60降到35，第1层战斗约3-4回合
    }

    // 获取基础伤害（略微降低，配合血量调整）
    getBaseDamage() {
        if (this.isBoss) return 18;   // 从20降到18
        if (this.isElite) return 11;  // 再降一档
        return 7;                     // 从8降到7
    }

    // 获取金币奖励
    getGoldReward() {
        if (this.isBoss) return 100;
        if (this.isElite) return 50;
        return 25;
    }

    // 获取名称
    getName() {
        const names = {
            // 普通考试
            'math_test': '数学考试',
            'chinese_test': '语文考试',
            'english_test': '英语考试',
            'physics_test': '物理考试',
            'chemistry_test': '化学考试',
            'biology_test': '生物考试',
            'history_test': '历史考试',
            'geography_test': '地理考试',
            
            // 精英考试
            'elite_math': '数学竞赛',
            'elite_chinese': '作文大赛',
            'elite_english': '英语演讲',
            'elite_physics': '物理竞赛',
            'elite_chemistry': '化学竞赛',
            'elite_biology': '生物竞赛',
            
            // Boss考试
            'gaokao_boss': '高考',
            'interview_boss': '面试官'
        };
        
        return names[this.type] || '未知考试';
    }

    // 获取描述
    getDescription() {
        const descriptions = {
            'math_test': '一道复杂的数学题，需要仔细计算',
            'chinese_test': '一篇深奥的古文，考验理解能力',
            'english_test': '一篇英语阅读理解，词汇量要求很高',
            'physics_test': '一道物理实验题，需要理解原理',
            'chemistry_test': '化学方程式配平，考验逻辑思维',
            'biology_test': '生物实验分析，需要观察能力',
            'history_test': '历史事件分析，需要记忆和理解',
            'geography_test': '地理知识问答，需要空间思维',
            
            'elite_math': '全国数学竞赛题目，难度极高',
            'elite_chinese': '全国作文大赛，文采要求很高',
            'elite_english': '英语演讲比赛，口语要求很高',
            'elite_physics': '物理竞赛题目，需要创新思维',
            'elite_chemistry': '化学竞赛实验，需要动手能力',
            'elite_biology': '生物竞赛实验，需要观察能力',
            
            'gaokao_boss': '人生最重要的考试，决定未来',
            'interview_boss': '职场面试，考验综合能力'
        };
        
        return descriptions[this.type] || '一场未知的考试';
    }

    // 初始化行为模式
    initializePattern() {
        switch (this.type) {
            case 'math_test':
                this.pattern = ['empower', 'multi3', 'defend'];
                break;
            case 'chinese_test':
                this.pattern = ['weaken', 'vulnerable', 'defend'];
                break;
            case 'english_test':
                this.pattern = ['multi', 'weaken', 'multi'];
                break;
            case 'physics_test':
                this.pattern = ['charge', 'attack', 'defend'];
                break;
            case 'chemistry_test':
                this.pattern = ['poison', 'attack', 'poison'];
                break;
            case 'biology_test':
                this.pattern = ['heal', 'attack', 'vulnerable'];
                break;
            case 'history_test':
                this.pattern = ['attack', 'weaken', 'empower'];
                break;
            case 'geography_test':
                this.pattern = ['defend', 'vulnerable', 'empower'];
                break;
                
            // 精英模式
            case 'elite_math':
                this.pattern = ['charge', 'multi3', 'weaken', 'special'];
                break;
            case 'elite_chinese':
                this.pattern = ['weaken', 'vulnerable', 'defend', 'special'];
                break;
            case 'elite_english':
                this.pattern = ['multi', 'weaken', 'multi', 'special'];
                break;
            case 'elite_physics':
                this.pattern = ['charge', 'attack', 'defend', 'special'];
                break;
            case 'elite_chemistry':
                this.pattern = ['poison', 'weaken', 'attack', 'special'];
                break;
            case 'elite_biology':
                this.pattern = ['heal', 'vulnerable', 'attack', 'special'];
                break;
                
            // Boss模式
            case 'gaokao_boss':
                this.pattern = ['charge', 'multi3', 'vulnerable', 'special', 'ultimate'];
                break;
            case 'interview_boss':
                this.pattern = ['empower', 'multi', 'weaken', 'special', 'ultimate'];
                break;
        }
    }

    // 行动（考虑眩晕状态）
    act(player) {
        if (this.health <= 0) return;
        
        // 检查眩晕状态
        if (this.isStunned()) {
            // 眩晕时跳过行动，并移除眩晕状态
            if (this.statusManager) {
                this.statusManager.removeStatus('眩晕');
            }
            return;
        }
        
        // 处理回合开始状态效果（中毒、灼烧等）
        this.processTurnStart();
        
        const action = this.pattern[this.patternIndex % this.pattern.length];
        this.patternIndex++;
        
        switch (action) {
            case 'attack':
                this.attack(player);
                break;
            case 'defend':
                this.defend();
                break;
            case 'multi':
                this.multiAttack(player);
                break;
            case 'multi3':
                this.multi3Attack(player);
                break;
            case 'poison':
                this.applyPoison(player);
                break;
            case 'weaken':
                this.applyWeaken(player);
                break;
            case 'vulnerable':
                this.applyVulnerable(player);
                break;
            case 'stun':
                this.applyStun(player);
                break;
            case 'empower':
                this.empowerSelf();
                break;
            case 'charge':
                this.chargeUp();
                break;
            case 'heal':
                this.healSelf();
                break;
            case 'special':
                this.specialAttack(player);
                break;
            case 'ultimate':
                this.ultimateAttack(player);
                break;
        }
        
        // 处理回合结束状态效果
        this.processTurnEnd();
    }

    // 普通攻击（考虑虚弱状态）
    attack(player) {
        this.damage = this.getDamageOutput();
        player.takeDamage(this.damage);
        // 注意：意图在getIntent()中动态计算，这里不再设置
    }

    // 防御
    defend() {
        this.block = Math.floor(this.baseDamage * 0.5);
        // 注意：意图在getIntent()中动态计算，这里不再设置
    }

    // 多段攻击（两段各为基础输出的60%）
    multiAttack(player) {
        const hit = Math.floor(this.getDamageOutput() * 0.6);
        this.damage = hit * 2;
        player.takeDamage(hit);
        player.takeDamage(hit);
    }

    // 三段攻击（各40%）
    multi3Attack(player) {
        const hit = Math.floor(this.getDamageOutput() * 0.4);
        this.damage = hit * 3;
        player.takeDamage(hit);
        player.takeDamage(hit);
        player.takeDamage(hit);
    }

    // 施加中毒
    applyPoison(player) {
        if (player.statusManager) {
            player.statusManager.addStatus(new Status('中毒', 3, 2, '受到持续伤害'));
        }
        this.damage = 0;
    }

    // 施加虚弱（减少玩家伤害）
    applyWeaken(player) {
        if (player.statusManager) {
            player.statusManager.addStatus(new Status('虚弱', 2, 1, '造成伤害降低'));
        }
        this.damage = 0;
    }

    // 施加易伤（玩家受伤增加）
    applyVulnerable(player) {
        if (player.statusManager) {
            player.statusManager.addStatus(new Status('易伤', 2, 1, '受到伤害增加'));
        }
        this.damage = 0;
    }

    // 施加眩晕（跳过玩家下一次行动回合）
    applyStun(player) {
        if (player.statusManager) {
            player.statusManager.addStatus(new Status('眩晕', 1, 1, '无法行动'));
        }
        this.damage = 0;
    }

    // 自我强化（临时提升输出）
    empowerSelf() {
        if (this.statusManager) {
            this.statusManager.addStatus(new Status('强化', 2, 2, '提升伤害'));
        }
        this.damage = 0;
    }

    // 蓄力（更强的强化）
    chargeUp() {
        if (this.statusManager) {
            this.statusManager.addStatus(new Status('强化', 2, 3, '蓄力'));
        }
        this.damage = 0;
    }

    // 自疗（10%最大生命）并施加易伤
    healSelf() {
        const healAmount = Math.floor(this.maxHealth * 0.1);
        this.health = Math.min(this.maxHealth, this.health + healAmount);
        this.damage = 0;
    }

    // 特殊攻击（考虑虚弱状态）
    specialAttack(player) {
        const baseSpecial = Math.floor(this.getDamageOutput() * 1.5);
        this.damage = baseSpecial;
        player.takeDamage(this.damage);
        // 注意：意图在getIntent()中动态计算，这里不再设置
    }

    // 终极攻击（考虑虚弱状态）
    ultimateAttack(player) {
        const baseUltimate = Math.floor(this.getDamageOutput() * 2);
        this.damage = baseUltimate;
        player.takeDamage(this.damage);
        // 注意：意图在getIntent()中动态计算，这里不再设置
    }

    // 受到伤害（考虑状态效果）
    takeDamage(damage) {
        // 计算易伤（受到的伤害增加）
        const vulnerable = this.statusManager ? this.statusManager.getStatusValue('易伤') : 0;
        const damageMultiplier = 1 + (vulnerable * 0.25); // 每层易伤+25%伤害
        const adjustedDamage = Math.floor(damage * damageMultiplier);
        
        const actualDamage = Math.max(0, adjustedDamage - (this.block || 0));
        this.health -= actualDamage;
        this.block = Math.max(0, (this.block || 0) - adjustedDamage);
        
        if (this.health < 0) {
            this.health = 0;
        }
    }

    // 造成伤害（考虑虚弱状态）
    getDamageOutput() {
        const weak = this.statusManager ? this.statusManager.getStatusValue('虚弱') : 0;
        const empower = this.statusManager ? this.statusManager.getStatusValue('强化') : 0;
        const damageReduction = weak * 0.25; // 每层虚弱-25%伤害
        const damageMultiplier = Math.max(0.25, 1 - damageReduction); // 最少25%伤害
        const base = Math.floor(this.baseDamage * damageMultiplier);
        return Math.max(0, base + empower * 2);
    }

    // 回合开始处理状态
    processTurnStart() {
        if (!this.statusManager) return;
        
        // 处理中毒（持续伤害）
        const poison = this.statusManager.getStatusValue('中毒');
        if (poison > 0) {
            this.health -= poison;
            if (this.health < 0) this.health = 0;
        }
        
        // 处理灼烧（持续伤害）
        const burn = this.statusManager.getStatusValue('灼烧');
        if (burn > 0) {
            this.health -= burn;
            if (this.health < 0) this.health = 0;
        }
    }

    // 回合结束处理状态
    processTurnEnd() {
        if (this.statusManager) {
            this.statusManager.processTurnEnd();
        }
    }

    // 检查是否眩晕（跳过回合）
    isStunned() {
        return this.statusManager && this.statusManager.hasStatus('眩晕');
    }

    // 获取意图（下一次行动）
    getIntent() {
        if (!this.pattern || this.pattern.length === 0) {
            return '准备中...';
        }
        
        // 计算下一次行动（基于当前的patternIndex）
        const nextAction = this.pattern[this.patternIndex % this.pattern.length];
        
        switch (nextAction) {
            case 'attack':
                const attackDamage = this.getDamageOutput();
                return `攻击 - 将造成${attackDamage}点伤害`;
            case 'defend':
                const block = Math.floor(this.getDamageOutput() * 0.5);
                return `防御 - 将获得${block}点护甲`;
            case 'multi':
                const hit = Math.floor(this.getDamageOutput() * 0.6);
                return `连击 - 2次各造成${hit}点伤害`;
            case 'multi3':
                const hit3 = Math.floor(this.getDamageOutput() * 0.4);
                return `连击 - 3次各造成${hit3}点伤害`;
            case 'poison':
                return `施加中毒 - 3回合每回合受到2点伤害`;
            case 'weaken':
                return `施加虚弱 - 2回合造成伤害降低`;
            case 'vulnerable':
                return `施加易伤 - 2回合受到伤害增加`;
            case 'stun':
                return `施加眩晕 - 跳过下一次行动`;
            case 'empower':
                return `自我强化 - 提升接下来2回合伤害`;
            case 'charge':
                return `蓄力 - 下回合攻击更危险`;
            case 'heal':
                return `自愈 - 恢复10%生命`;
            case 'special':
                const specialDamage = Math.floor(this.getDamageOutput() * 1.5);
                return `特殊攻击 - 将造成${specialDamage}点伤害`;
            case 'ultimate':
                const ultimateDamage = Math.floor(this.getDamageOutput() * 2);
                return `终极攻击 - 将造成${ultimateDamage}点伤害`;
            default:
                return '准备中...';
        }
    }

    // 检查是否死亡
    isDead() {
        return this.health <= 0;
    }
}

// 敌人工厂类
class EnemyFactory {
    static createEnemy(type, floor, isElite = false, isBoss = false, difficultyTier = 1) {
        return new Enemy(type, floor, isElite, isBoss, difficultyTier);
    }
    
    static getRandomNormalEnemy(floor, difficultyTier = 1) {
        const normalTypes = [
            'math_test', 'chinese_test', 'english_test', 'physics_test',
            'chemistry_test', 'biology_test', 'history_test', 'geography_test'
        ];
        const type = normalTypes[Math.floor(Math.random() * normalTypes.length)];
        return new Enemy(type, floor, false, false, difficultyTier);
    }
    
    static getEliteEnemy(floor, difficultyTier = 1) {
        const eliteTypes = this.getEliteTypesForFloor(floor);
        const type = eliteTypes[Math.floor(Math.random() * eliteTypes.length)];
        return new Enemy(type, floor, true, false, difficultyTier);
    }
    
    static getBossEnemy(floor, difficultyTier = 1) {
        const bossTypes = ['gaokao_boss', 'interview_boss'];
        const type = bossTypes[Math.floor(Math.random() * bossTypes.length)];
        return new Enemy(type, floor, false, true, difficultyTier);
    }
    
    static getEliteTypesForFloor(floor) {
        if (floor === 4) return ['elite_math', 'elite_chinese'];
        if (floor === 8) return ['elite_english', 'elite_physics'];
        if (floor === 12) return ['elite_chemistry', 'elite_biology'];
        return [];
    }
}
